<template>
  <el-form :inline="true" :model="ruleForm" class="demo-form-inline">
    <el-form-item label="客户">
      <el-select placeholder="请选择客户" clearable v-model="ruleForm.organId">
        <el-option v-for="customer in customers" :key="customer.id" :label="customer.supName" :value="customer.supId" />
      </el-select>
    </el-form-item>
    <el-form-item label="单据编号">
      <el-input v-model="ruleForm.number" placeholder="自动生成单据编号" readonly></el-input>
    </el-form-item>
    <el-form-item label="创建时间">
      <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>
    <el-form-item label="关联订单">
      <el-input v-model="ruleForm.linkNumber" style="width: 240px" suffix-icon="Search"
        v-perm:sale:sale_in:insert:associateorder="handleIconClick" />
    </el-form-item>
    <div class="user-index-body-form-btn-item">
      <div class="ant-row-flex" style="display: flex; align-items: center;">
        <div class="ant-col" style="margin-right: 10px;">
          <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain>扫码录入</el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain v-perm:sale:sale_in:insert:inorderfind="insert">
            <el-icon style="margin-right: 5px;">
              <Clock />
            </el-icon>
            历史单据
          </el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 1450px">
        <el-table-column type="selection" width="55" v-model="selectedItems" />
        <el-table-column v-if="showIdColumn" prop="id" label="id" width="170" />
        <el-table-column width="120">
          <template #default="{ row }">
            <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
              v-perm:sale:sale_in:insert:salein="Saleinorder">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="仓库" width="120">
          <template #default="{ row }">
            <el-select v-model="row.dname" clearable style="width: 280px; margin-left: 10px;" placeholder="请选择仓库"
              @change="onChangeDepotSelect(row.dname, row)">
              <el-option v-for="depot in depots" :key="depot.id" :label="depot.name" :value="depot.id" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="条码" width="120">
          <template #default="{ row }">
            <el-input v-model="row.barCode"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="名称" width="120">
          <template #default="{ row }">
            <el-input v-model="row.materialName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="120">
          <template #default="{ row }">
            <el-input v-model="row.standard"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="120">
          <template #default="{ row }">
            <el-input v-model="row.totalOperNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.commodityUnit"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <el-input v-model="row.operNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="{ row }">
            <el-input v-model="row.wholesaledecimal"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.allPrice"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税率" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxRate" @input="updateTax(row)" placeholder="输入税率"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxMoney" placeholder="税额" readonly></el-input>
          </template>
        </el-table-column>
        <el-table-column label="价格合计" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxLastMoney" placeholder="价税合计" readonly></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="100">
          <template #default="{ row }">
            <el-input v-model="row.totalOut"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item label="合计金额：" style="margin-right: 100px;">
        <el-input :value="calculateTotalPrice()" readonly style="width: 240px" v-model="ruleForm.totalPrice"></el-input>
      </el-form-item>
      <div class="index-body tb">
        <el-form-item label="优惠率：" style="margin-right: 120px;">
          <el-input v-model="ruleForm.discount" @input="updateDiscountedData" style="width: 185px"></el-input>
        </el-form-item>
        <el-form-item label="本次欠款：" style="margin-right: 100px;">
          <el-input style="width: 240px" v-model="ruleForm.amountDue" readonly></el-input>
        </el-form-item>
        <el-form-item label="本次收款：" style="margin-right: 100px;">
          <el-input style="width: 240px" v-model="ruleForm.amountReceived" @input="handleChangeAmount"></el-input>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.changeAmount !== 0 && ruleForm.changeAmount !== null && ruleForm.changeAmount !== undefined"
          label="扣除定金：" style="margin-right: 100px;">
          <el-input style="width: 240px" v-model="ruleForm.changeAmount" @input="handleChangeAmount"></el-input>
        </el-form-item>
        <el-form-item label="优惠后金额：">
          <el-input :value="calculateDiscountedAmount()" style="width: 240px" readonly></el-input>
        </el-form-item>
        <el-form-item label="销售人员：" style="margin-right: 100px;">
          <el-select v-model="ruleForm.salesMan" multiple filterable allow-create default-first-option
            :reserve-keyword="false" placeholder="请选择销售人员" style="width: 240px">
            <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName" :value="persons.perId" />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="结算账户：" style="margin-right: 120px;">
        <el-select clearable style="width: 200px; " placeholder="请选择客户" v-model="ruleForm.accountId">
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
        </el-select>
      </el-form-item>
      <div class="ant-coloery" style="margin-right: 10px;">
        <el-form-item label="附件：">
          <el-button plain>
            <el-icon style="margin-right: 10px;">
              <MessageBox />
            </el-icon>上传附件
          </el-button>
        </el-form-item>
      </div>
    </div>
  </el-form>
  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
    style="margin-left: 350px;margin-top: 200px">
    <router-view @close="close" @saveSaleinorder="saveSaleinorder" :data="data" @ert="saveErt" @proty="proty"
      :currentDepotId="currentDepotId"></router-view>
  </el-dialog>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';
const selectedItems = ref([]); // 用于存储选中的商品
const calculateTotalPrice = () => {
  const total = tableData.value.reduce((total, row) => {
    const price = parseFloat(row.allPrice) || 0; // 确保是 allPrice
    return total + price;
  }, 0);

  return total.toFixed(2); // 保留两位小数
};

// updateTax 函数
const updateTax = (row) => {
  const unitPrice = parseFloat(row.wholesaledecimal) || 0;
  const quantity = parseFloat(row.operNumber) || 0;
  const taxRate = parseFloat(row.taxRate) || 0;
  const taxMoney = (unitPrice * quantity * (taxRate / 100)).toFixed(2);
  row.taxMoney = taxMoney;
  const taxLastMoney = (unitPrice * quantity + parseFloat(taxMoney)).toFixed(2);
  row.taxLastMoney = taxLastMoney;
  // 重新计算合计金额
  calculateTotalPrice();
};
const calculateDiscountedAmount = () => {
  const totalAmount = calculateTotalPrice(); // 获取合计金额
  const discountRate = parseFloat(ruleForm.value.discount) || 0; // 获取优惠率
  const discountAmount = totalAmount * (discountRate / 100); // 计算优惠金额
  return (totalAmount - discountAmount).toFixed(2); // 返回优惠后金额并保留两位小数
};

const visible = ref(false);
const title = ref("");
const data = ref({});
const ruleForm = ref({
  linkNumber: '',
  deposit: '',
  discount: 0, // 保持原来的discount
  discountMoney: 0, // 初始化这个值
  discountLastMoney: 0, // 初始化这个值
  totalAmount: 0,
  changeAmount: 0,
  amountDue: 0,
  amountReceived: 0,
  discountRate: 0, // 添加discountRate
  paymentDiscount: 0, // 添加paymentDiscount
  taxLastMoney: '0',
  totalPrice:''
  
});


const close = () => {
  visible.value = false;
};
// 表格数据
const tableData = ref([
  { barCode: '', categoryName: '', color: '', commodityUnit: '', materialName: '', mfrs: '', model: '', sku: '', standard: '', totalIn: '', totalOperNumber: '', totalOut: '', wholesaledecimal: '', basicnumber: '', allprice: '', linkNumber: '', taxLastMoney: '' }
]);

const Saleinorder = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}
const handleChangeAmount = () => {
  const amountReceived = parseFloat(ruleForm.value.amountReceived) || 0; // 本次收款
  const discountLastMoney = calculateDiscountedAmount(); // 优惠后金额，通过计算获取

  // 计算本次欠款
  ruleForm.value.amountDue = (discountLastMoney - amountReceived).toFixed(2); // 优惠后金额减去本次收款
};

const loadDataAndPrepareForm = () => {
  // 假设这里有代码加载数据
  const totalAmount = tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0);
  ruleForm.value.totalAmount = totalAmount; // 确保在计算之前总金额已经设定

  updateDiscountedData(); // 计算折扣
};

// 在页面加载时调用
onMounted(loadDataAndPrepareForm);
const updateDiscountedData = () => {

  handleChangeAmount();
};



const accounts = ref([]); // 存储结算账户数据
const loadAccounts = () => {
  request({
    url: '/basic/account/list',
    method: 'get'
  }).then(res => {

    accounts.value = res.data; // 更新结算账户数据
  }).catch(err => {
    console.error(err);
  });
};
loadAccounts();
const submitForm = () => {
  const totalPrice = tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0);
  ruleForm.value.discountLastMoney = calculateDiscountedAmount();
  if (!ruleForm.value.linkNumber) {
    // 没有关联订单，执行另一个新增操作
    // 这里调用另一个新增的方法，假设为 anotherInsert
    anotherInsert();
  } else {
    // 有关联订单，正常提交表单
    const data = {
      erpDepotHead: {
        type: '出库',
        subType: '销售',
        number: ruleForm.value.number,
        organId: ruleForm.value.organId,
        creator: '1',
        accountId: ruleForm.value.accountId,
        totalPrice:totalPrice,
        discount: ruleForm.value.discountRate,
        discountMoney: ruleForm.value.paymentDiscount,
        discountLastMoney: ruleForm.value.discountLastMoney,
        linkNumber: ruleForm.value.linkNumber,
        status: '1',
        paytype: '现付',
        deposit: ruleForm.value.deposit,
        otherMoney: ruleForm.value.otherMoney,
        changeAmount: ruleForm.value.amountReceived,
        salesMan: ruleForm.value.salesMan.join(','),
      },
      erpDepotItems: tableData.value.map(row => ({
        materialId: row.mid,
        materialExtendId: row.aid,
        materialUnit: row.commodityUnit,
        depotId: row.dname,
        sku: row.sku,
        operNumber: row.operNumber,
        unitPrice: row.wholesaledecimal,
        allPrice: row.allPrice,
        remark: row.remark || '',
        taxRate: row.taxRate,
        taxMoney: row.taxMoney,
        taxLastMoney: row.taxLastMoney,
        linkId: row.id,
      }))
    };

    // 添加请求
    request({
      url: '/sale/insertck',
      method: 'post',
      data: data,
      headers: { 'Content-Type': 'application/json' }
    }).then(res => {
      console.log(res);
      ElMessage.success('提交成功');
    }).catch(err => {
      console.error(err);
      ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
    });
  }
};

const anotherInsert = () => {
  ruleForm.value.discountLastMoney = calculateDiscountedAmount();
  const totalPrice = tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0);

  const data = {
    erpDepotHead: {
      type: '出库',
      subType: '销售',
      number: ruleForm.value.number,
      organId: ruleForm.value.organId,
      creator: '1',
      accountId: ruleForm.value.accountId,
      totalPrice: totalPrice,
      discount: ruleForm.value.discountRate,
      discountMoney: ruleForm.value.paymentDiscount,
      discountLastMoney: ruleForm.value.discountedAmount,
      status: '1',
      paytype: '现付',
      deposit: ruleForm.value.deposit,
      otherMoney: ruleForm.value.otherMoney,
      changeAmount: ruleForm.value.amountReceived,
      salesMan: ruleForm.value.salesMan.join(','),
    },
    erpDepotItems: tableData.value.map(row => ({
      materialId: row.mid,
      materialExtendId: row.aid,
      materialUnit: row.commodityUnit,
      depotId: row.dname,
      sku: row.sku,
      operNumber: row.operNumber,
      unitPrice: row.wholesaledecimal,
      allPrice: row.allPrice,
      remark: row.remark || '',
      taxRate: row.taxRate,
      taxMoney: row.taxMoney,
      taxLastMoney: row.taxLastMoney,
    }))
  };
  request({
    url: '/sale/insertck2',
    method: 'post',
    data: data,
    headers: { 'Content-Type': 'application/json' }
  }).then(res => {
    console.log(res);
    ElMessage.success('提交成功');
  }).catch(err => {
    console.error(err);
    ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
  });
}


const person = ref({})
const personfin = () => {
  request({
    url: '/basic/person/list',
    method: 'get'

  }).then(res => {
    person.value = res.data
    console.log(res)
  })
}
personfin();
const handleIconClick = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}


let save = ref([])

const proty = (item) => {
  console.log("proty被调用", item);
  ruleForm.value.linkNumber = item.number;
  ruleForm.value.changeAmount = item.changeAmount;
  ruleForm.value.discount = item.discount;
  ruleForm.value.discountLastMoney = item.discountLastMoney;
  ruleForm.value.discountMoney = item.discountMoney;


}

const customers = ref([]);
const loadCustomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {
    customers.value = res.data;
  }).catch(err => {
    console.error(err);
  });
};
loadCustomers();
const depots = ref([]);
const currentDepotId = ref('');


const loadDepot = () => {
  request({
    url: '/depot/list',
    method: 'get',
  }).then((res) => {
    depots.value = res.data; // 更新仓库数据
  }).catch((err) => {
    console.error(err);
  });
};
loadDepot();
// 页面加载时生成订单编号
// 
onMounted(() => {
  // 从本地存储获取当前的订单编号，如果不存在则默认为1
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);

  // 自增
  currentOrderNumber++;

  // 格式化为11位数字并添加前缀
  const formattedOrderNumber = `XSCK${currentOrderNumber.toString().padStart(11, '0')}`;

  // 将生成的订单编号赋值到表单
  ruleForm.value.number = formattedOrderNumber;

  // 将新的订单编号存储到本地存储中，便于下次使用
  localStorage.setItem('orderNumber', currentOrderNumber.toString());
});


const saveErt = (item) => {
  tableData.value = item.map(item => ({
    barCode: item.barCode,
    categoryName: item.categoryName,
    color: item.color,
    commodityUnit: item.commodityUnit,
    materialName: item.materialName,
    mfrs: item.mfrs,
    model: item.model,
    sku: item.sku,
    standard: item.standard,
    totalIn: item.totalIn,
    totalOperNumber: item.totalOperNumber,
    totalOut: item.totalOut,
    wholesaledecimal: item.wholesaledecimal,
    basicnumber: item.basicnumber,
    allPrice: item.allPrice,
    mid: item.mid,
    aid: item.aid,
    id: item.id,
    operNumber: 1,
    taxRate: item.taxRate,
    taxMoney: item.taxMoney,
    taxLastMoney: item.taxLastMoney,

  }));
  console.log("saveErt被调用", item);
}

// 接收并显示保存的数据
const addRow = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allPrice: '',
    mid: '',
    aid: '',
    id: '',
    operNumber: 1, // 默认数量
    taxRate: '',
    taxMoney: '',
    taxLastMoney: '',
    dname: '',
    depotId: '' // 新行的仓库默认空值
  });
};

const onChangeDepotSelect = (depotId) => {
  currentDepotId.value = depotId; // 更新当前选择的仓库 ID
};


const saveSaleinorder = (selectedItems) => {
  selectedItems.forEach(item => {
    const emptyRowIndex = tableData.value.findIndex(row => !row.barCode); // 查找第一个空行
    if (emptyRowIndex !== -1) {
      // 将选中的商品填入空行
      const row = tableData.value[emptyRowIndex];
      Object.assign(row, {
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    } else {
      // 添加新行
      tableData.value.push({
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    }
  });
  console.log("已添加商品:", selectedItems);
};




const insert = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
};
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
